package com.huhu.contact;

import com.huhu.contact.slice.ContactPersonAbilitySlice;

import com.huhu.contact.utils.PreferenceUtils;
import com.huhu.contact.utils.Toast;
import com.huhu.contact.widget.controller.FormController;
import com.huhu.contact.widget.controller.FormControllerManager;
import ohos.aafwk.ability.*;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.bundle.IBundleManager;
import ohos.global.configuration.Configuration;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.security.SystemPermission;
import ohos.utils.net.Uri;
import ohos.utils.zson.ZSONObject;

import java.util.List;

public class ContactPersonAbility extends Ability {
    protected static final HiLogLabel loglabel = new HiLogLabel(HiLog.LOG_APP, 0x11102, ContactPersonAbility.class.getName());
    private LocaleChangeListener localeChangeListener;
    private String topWidgetSlice;
    public static final int DEFAULT_DIMENSION_2X2 = 2;
    public static final int DIMENSION_1X2 = 1;
    public static final int DIMENSION_2X4 = 3;
    public static final int DIMENSION_4X4 = 4;
    private static final int INVALID_FORM_ID = -1;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(ContactPersonAbilitySlice.class.getName());
//        if (intentFromWidget(intent)) {
//            topWidgetSlice = getRoutePageSlice(intent);
//            if (topWidgetSlice != null) {
//                setMainRoute(topWidgetSlice);
//            }
//        }
//        stopAbility(intent);
//        requestPermissions();
    }

    private void requestPermissions() {
        if (verifySelfPermission("android.permission.CALL_PHONE") != IBundleManager.PERMISSION_GRANTED) {
            // 应用未被授予权限
            if (canRequestPermission("android.permission.CALL_PHONE")) {
                // 是否可以申请弹框授权(首次申请或者用户未选择禁止且不再提示)
                requestPermissionsFromUser(new String[]{"android.permission.CALL_PHONE"}, 100);
            } else {
//                // 显示应用需要权限的理由，提示用户进入设置授权
//                // 权限被拒绝
//                Toast.makeToast(this, "请开启权限", Toast.TOAST_SHORT).show();
            }
        } else {
            // 权限已被授予

        }

    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 100:// 匹配requestPermissions的requestCode
                if (grantResults.length > 0 && grantResults[0] == IBundleManager.PERMISSION_GRANTED) {
                    // 权限被授予

                } else {
                    // 权限被拒绝
                    Toast.makeToast(this, "请开启相关权限", Toast.TOAST_SHORT).show();
                }
                break;
            default:
                break;
        }
    }


    @Override
    public void onConfigurationUpdated(Configuration configuration) {
        super.onConfigurationUpdated(configuration);
        localeChangeListener.onLocaleChange(configuration);
    }

    public void setLocaleChangeListener(LocaleChangeListener localeChangeListener) {
        this.localeChangeListener = localeChangeListener;
    }

    public void confirmUpdateForm(FormBindingData formBindingData) {
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        List<Long> allFormIdFromSharePreference = formControllerManager.getAllFormIdFromSharePreference();
        if (allFormIdFromSharePreference == null || allFormIdFromSharePreference.isEmpty()) return;
        Long formId = allFormIdFromSharePreference.get(0);
        try {
            updateForm(formId,formBindingData);
        } catch (FormException e) {
            e.printStackTrace();
        }
    }


    /**
     * The LocaleChangeListener
     */
    public static class LocaleChangeListener {
        /**
         * The onLocaleChange
         *
         * @param configuration configuration
         */
        public void onLocaleChange(Configuration configuration) {
        }
    }

    @Override
    protected ProviderFormInfo onCreateForm(Intent intent) {
        HiLog.info(loglabel, "onCreateForm");
        long formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, INVALID_FORM_ID);
        String formName = intent.getStringParam(AbilitySlice.PARAM_FORM_NAME_KEY);
        int dimension = intent.getIntParam(AbilitySlice.PARAM_FORM_DIMENSION_KEY, DEFAULT_DIMENSION_2X2);
        HiLog.info(loglabel, "onCreateForm: formId=" + formId + ",formName=" + formName);
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        FormController formController = formControllerManager.getController(formId);
        formController = (formController == null) ? formControllerManager.createFormController(formId,
                formName, dimension) : formController;
        if (formController == null) {
            HiLog.error(loglabel, "Get null controller. formId: " + formId + ", formName: " + formName);
            return null;
        }
        return formController.bindFormData();
    }

    @Override
    protected void onUpdateForm(long formId) {
        HiLog.info(loglabel, "onUpdateForm");
        super.onUpdateForm(formId);
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        FormController formController = formControllerManager.getController(formId);
        formController.updateFormData(formId);

    }

    @Override
    protected void onDeleteForm(long formId) {
        HiLog.info(loglabel, "onDeleteForm: formId=" + formId);
        super.onDeleteForm(formId);
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        formControllerManager.deleteFormController(formId);
    }

    @Override
    protected void onTriggerFormEvent(long formId, String message) {
        super.onTriggerFormEvent(formId, message);
        HiLog.info(loglabel, "onTriggerFormEvent: " + message);
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        FormController formController = formControllerManager.getController(formId);
        formController.onTriggerFormEvent(formId, message);
        ZSONObject params = ZSONObject.stringToZSON(message);
        String action = params.getString("action");
        String phoneNumber = params.getString("phoneNumber");
        HiLog.info(loglabel, "onTriggerFormEvent: action:" + action);

        String urgentPersonStr = PreferenceUtils.getString(this, "urgentPerson", "");
        ZSONObject zsonObject = ZSONObject.stringToZSON(urgentPersonStr);
        switch (action) {
            case "urgentCall1":
                String urgentPhone1 = zsonObject.getString("urgentPhone1");
                Intent intent1 = new Intent();
                Operation operation1 = new Intent.OperationBuilder()
                        .withAction(ohos.utils.IntentConstants.ACTION_DIAL) // 系统应用拨号盘
                        .withUri(Uri.parse("tel:" + urgentPhone1)) // 设置号码
                        .withFlags(2)
                        .build();
                intent1.setOperation(operation1);
                startAbility(intent1);
                break;
            case "urgentCall2":
                String urgentPhone2 = zsonObject.getString("urgentPhone2");
                Intent intent2 = new Intent();
                Operation operation2 = new Intent.OperationBuilder()
                        .withAction(ohos.utils.IntentConstants.ACTION_DIAL) // 系统应用拨号盘
                        .withUri(Uri.parse("tel:" + urgentPhone2)) // 设置号码
                        .withFlags(2)
                        .build();
                intent2.setOperation(operation2);
                // 启动Ability

                startAbility(intent2);
                break;
            default:
                break;
        }
    }

    private void doCall(String destinationNum) {
        HiLog.info(loglabel, "doCall() destinationNum:" + destinationNum);
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withAction(ohos.utils.IntentConstants.ACTION_DIAL) // 系统应用拨号盘
//                .withBundleName(context.getCallingBundle()) // 应用拨号选择器
                .withUri(Uri.parse("tel:" + destinationNum)) // 设置号码
                .withFlags(2)
                .build();
        intent.setOperation(operation);
        // 启动Ability
        startAbility(intent, 10);

    }

    @Override
    public void onNewIntent(Intent intent) {
        if (intentFromWidget(intent)) { // Only response to it when starting from a service widget.
            String newWidgetSlice = getRoutePageSlice(intent);
            if (topWidgetSlice == null || !topWidgetSlice.equals(newWidgetSlice)) {
                topWidgetSlice = newWidgetSlice;
                restart();
            }
        }
    }

    private boolean intentFromWidget(Intent intent) {
        long formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, INVALID_FORM_ID);
        return formId != INVALID_FORM_ID;
    }

    private String getRoutePageSlice(Intent intent) {
        long formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, INVALID_FORM_ID);
        if (formId == INVALID_FORM_ID) {
            return null;
        }
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        FormController formController = formControllerManager.getController(formId);
        if (formController == null) {
            return null;
        }
        Class<? extends AbilitySlice> clazz = formController.getRoutePageSlice(intent);
        if (clazz == null) {
            return null;
        }
        return clazz.getName();
    }
}
